package com.mezz.bones.framework.gateway.config;

import com.mezz.bones.framework.gateway.loadbalancer.MetadataVersionLoadBalancer;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.loadbalancer.core.ReactorLoadBalancer;
import org.springframework.cloud.loadbalancer.core.ServiceInstanceListSupplier;
import org.springframework.cloud.loadbalancer.support.LoadBalancerClientFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.env.Environment;

/**
 * 基于元数据版本的负载均衡器配置类
 * 为指定服务配置基于Nacos元数据version字段的负载均衡策略
 * 通过@LoadBalancerClient注解绑定到特定服务
 */
//@Configuration
//@ConditionalOnBean(LoadBalancerClientBindConfiguration.class)
public class MetadataVersionLoadBalancerConfig {

    private static final Logger log = LoggerFactory.getLogger(MetadataVersionLoadBalancerConfig.class);

    /**
     * 配置ServiceInstanceListSupplier，用于从Nacos获取服务实例列表
     */

    /**
     * 配置自定义负载均衡器
     * 基于Nacos元数据version字段进行负载均衡
     * 在请求时初始化，此时能正确获取到服务名
     */
    @Bean
    public MetadataVersionLoadBalancer reactorServiceInstanceLoadBalancer(
            Environment environment,
            LoadBalancerClientFactory loadBalancerClientFactory) {

        String name = environment.getProperty(LoadBalancerClientFactory.PROPERTY_NAME);

        log.info("为服务配置自定义负载均衡器: MetadataVersionLoadBalancer, 当前服务: [{}]", name);

        return new MetadataVersionLoadBalancer(
                loadBalancerClientFactory.getLazyProvider(name, ServiceInstanceListSupplier.class),
                name
        );
    }

}